<template>
  <li>
    <label>
      <input
          type="checkbox"
          :checked="obj.completed"
          @change="change(obj.id)"
      />
      <span v-show="!obj.isEdit">{{ obj.name }}</span>
      <input type="text"
             v-show="obj.isEdit"
             :value="obj.name"
             ref="inputTitle"
             @blur="handlerBlur(obj, $event)">
    </label>
    <button class="btn btn-danger" @click="deleteTodo(obj.id)">删除</button>
    <button class="btn btn-edit"
            v-show="!obj.isEdit"
            @click="editTodo(obj, $event)">编辑</button>
  </li>
</template>

<script>
import pubsub from "pubsub-js"

export default {
  name: "MyItem",
  props: ["obj",],
  methods: {
    change(id) {
      // this.checkTodo(id);
      this.$bus.$emit("checkTodo", id)
    },
    deleteTodo(id) {
      // this.deleteItem(id);
      if (confirm("确定删除吗？")) {
        pubsub.publish("deleteItem", id)
      }
    },
    editTodo(todo) {
      if (Object.prototype.hasOwnProperty.call(todo, "isEdit")) {
        todo.isEdit = true
      } else {
        this.$set(todo, 'isEdit', true)
      }
      // 切换到输入框，并获取焦点
      this.$nextTick(function(){
        this.$refs.inputTitle.focus()
      })
    },
    handlerBlur(todo, e) {
      todo.isEdit = false
      console.log("editTodo", todo, e.target.value)
      if(!e.target.value.trim){
        alert("todo 不能为空")
        return
      }
      this.$bus.$emit("editTodo", todo.id, e.target.value)
    }
  },
};
</script>

<style scoped>
/*item*/
li {
  list-style: none;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border-bottom: 1px solid #ddd;
}

li label {
  float: left;
  cursor: pointer;
}

li label li input {
  vertical-align: middle;
  margin-right: 6px;
  position: relative;
  top: -1px;
}

li button {
  float: right;
  display: none;
  margin-top: 3px;
}

li:before {
  content: initial;
}

li:last-child {
  border-bottom: none;
}

li:hover {
  background-color: #ddd;
}

li:hover button {
  display: block;
}
</style>